package com.xuyuan.valid;


import jakarta.validation.Constraint;
import jakarta.validation.ConstraintValidator;
import jakarta.validation.ConstraintValidatorContext;
import jakarta.validation.Payload;

import java.lang.annotation.ElementType;
import java.lang.annotation.Retention;
import java.lang.annotation.RetentionPolicy;
import java.lang.annotation.Target;

/**
 * 定义一个自定义校验注释，来判断所注释的字符串是否全为大写或全为小写
 */
@Target({ElementType.FIELD, ElementType.PARAMETER})
@Retention(RetentionPolicy.RUNTIME)
@Constraint(validatedBy = CustomValidator.CheckCaseValidator.class)
public @interface CustomValidator {

    CaseMode value() default CaseMode.UPPER;

    String message() default "must be all upper case or all lower case";

    /**
     * 分组，默认为空。加对应的分组，校验的时候加上对应的分组，就只会校验在分组内的场景
     */
    Class<?>[] groups() default {};

    Class<? extends Payload>[] payload() default {};

    enum CaseMode {
        UPPER, LOWER;
    }

    /**
     * 分组
     */
    interface GroupOne {
    }

    interface GroupTwo {
    }

    class CheckCaseValidator implements ConstraintValidator<CustomValidator, String> {

        private CaseMode caseMode;

        @Override
        public void initialize(CustomValidator constraintAnnotation) {
            this.caseMode = constraintAnnotation.value();
        }

        @Override
        public boolean isValid(String value, ConstraintValidatorContext context) {
            if (value == null) return true;
            if (caseMode == CaseMode.UPPER) return value.equals(value.toUpperCase());
            else return value.equals(value.toLowerCase());
        }
    }

}
